<template>
  <view>
    <image :src="url" @tap="previewImage(url)" mode="widthFix"></image>
    <view class="margin-top padding text-sm">
      <text>请先仔细阅读老年学员入学协议后，再签名</text>
      <text class="text-red margin-left" v-if="countdown !== 0">{{ countdown }}s</text>
    </view>
    <view class="padding flex justify-around">
      <template v-if="!isFinishSign">
        <button class="cu-btn bg-blue" :disabled="countdown !== 0 || signSelf" @tap="doSign('self')">本人签名</button>
        <button class="cu-btn bg-red" :disabled="countdown !== 0 || signOthers" @tap="doSign('others')">直系家属签名</button>
      </template>
      <button class="cu-btn bg-green" v-else @tap="back">完成签名，点击返回</button>
    </view>

  </view>
</template>

<script lang="ts" setup>
import {usePreview} from "../../utils/usePreview";
import {computed, onBeforeMount, onBeforeUnmount, ref, watch} from "vue";
import {onLoad} from "@dcloudio/uni-app";

const url = ref(import.meta.env.VITE_CNS_URL)
const {previewImage} = usePreview()

const countdown = ref(10)
const signSelf = ref(false)
const signOthers = ref(false)
const isFinishSign = computed(() => signSelf.value && signOthers.value)

function doSign(type: 'self' | 'others') {
  uni.navigateTo({
    url: `/pages/sign/index?type=${type}&url=${url.value}`,
    success: () => {
      uni.$on('submitSign', (res) => {
        url.value = res.url
        switch (res.from){
          case 'self': {
            signSelf.value = true
            break
          }

          case 'others': {
            signOthers.value = true
            break
          }
        }
      })
    }
  })
}

onBeforeUnmount(() => {
  uni.$off('submitSign')
})

watch(() => isFinishSign.value, (value) => {
  if (value){
    uni.$emit('finishSign',url.value)
  }
})

onLoad((option:any) => {
  const interval = setInterval(() => {
    if (countdown.value === 0){
      clearInterval(interval)
      return
    }
    countdown.value--
  },1000)
})

function back() {
  uni.navigateBack()
}

</script>

<style scoped>
image{
  width: 100vw;
}
</style>
